<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Schema;
use DB;

/* 实验完成后上传数据 */

class UploadGwDataJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data_input_job;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data_input_job)
    {
        Log::info('---------------UploadGwDataJob----------Start:');
        Log::info($data_input_job);
        $this->data_input_job = $data_input_job;
    }

    /**
     * Execute the job.
     *
     * @return bool
     */
    public function handle()
    {
        sleep(2);//有必要睡眠2秒，防止频繁请求获取ip api出错

        //通过编码来判断该样品是否已做完试验，做完试验上传数据到风控，若第一项不合格也上传数据
        $data_input_job = $this->data_input_job;

        $third_id = DB::table('a_third_data')->where('bar_code',$data_input_job)->orWhere('third_id2',$data_input_job)->value('third_id');
        $sample_info = DB::table('a_sample_info')->where('bar_code', $data_input_job)->orWhere('third_id', $data_input_job)->orderBy('id','desc')->first(); //山东国网工器具编号
        if(!$third_id || !$sample_info){
            Log::info('UploadGwDataJob:$third_id or $sample_info Missing Parameter');
            return false;
        }
        //判断是否做完，或者第一项实验项目不合格
        $res = DB::table('a_item_data')->where('sample_info_id',$sample_info->id)->get()->toArray();
        if(!$res){
            Log::info($data_input_job.'->该样品没有试验项目！！');
            return false;
        }
        $biaozhi = 0;   //标记是否全部完成变量
        /*foreach($res as $key=>$val){        //结论,0-不符合，1-符合，2-未录入,3-未试验
            if($val->res == 1){
                $biaozhi = 1;
            }
        }*/
        $res_arr = array_values(array_column($res,'res','item_id'));
        if(in_array(0,$res_arr)){
            $biaozhi = 1;
        }elseif(in_array(2,$res_arr)){
            $biaozhi = 0;
        }else{
            $biaozhi = 1;
        }
        Log::info('On-Off:'.$biaozhi);
        //调用上传功能
        if($biaozhi){
            //批次表状态修改为试验完成
            $CS= DB::table('a_contract')->where('id', $sample_info->contract_id)->where('status',0)->update(['status' =>8]);
            Log::info($sample_info->contract_id.'a_contract_status='.$CS);
            $sample_ids = [$sample_info->id];
            $third_ids =[$third_id];
            request()->offsetSet('third_ids',$third_ids);
            request()->offsetSet('sample_ids',$sample_ids);
            $thirdCon = new \App\Http\Controllers\Admin\ThirdController();
            $uploadRes = $thirdCon->uploadRes(); //成功返回1，不成功返回错误信息
            Log::info('------------------上传结束，状态码：'.$uploadRes);
        }else{
            Log::info('样品编号：'.$data_input_job.' 尚未做完全部试验项目！！');
        }

    }

}
